package login

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/logic/user"
	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/duke-git/lancet/v2/netutil"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx               context.Context
	svcCtx            *svc.ServiceContext
	r                 *http.Request
	getUserMenusLogic *user.GetUserMenusLogic
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *UserLoginLogic {
	return &UserLoginLogic{
		Logger:            logx.WithContext(ctx),
		ctx:               ctx,
		svcCtx:            svcCtx,
		r:                 r,
		getUserMenusLogic: user.NewGetUserMenusLogic(ctx, svcCtx, r),
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginReq) (resp *types.UserLoginResp, err error) {
	// 登录
	loginResp, err := l.svcCtx.LoginRpc.Login(l.ctx, &syspb.LoginReq{
		UserName:   req.Username,
		Password:   req.Password,
		VerifyCode: req.VerifyCode,
		VerifyKey:  req.VerifyKey,
		Ip:         netutil.GetRequestPublicIp(l.r),
		UserAgent:  l.r.UserAgent(),
	})
	if err != nil {
		return nil, err
	}

	var (
		userInfo    = new(types.SysUser)
		token       = ""
		menuList    = make([]*types.UserMenuTree, 0)
		permissions = make([]string, 0)
	)

	if loginResp.GetUser() != nil {
		_ = copier.Copy(userInfo, loginResp.GetUser())
	}
	if loginResp.GetToken() != "" {
		token = loginResp.GetToken()
	}
	if len(loginResp.GetTree()) != 0 {
		menuList = l.getUserMenusLogic.GetUserMenuTree(loginResp.GetTree())
	}
	if len(loginResp.GetPermissions()) != 0 {
		permissions = loginResp.GetPermissions()
	}

	return &types.UserLoginResp{
		UserInfo:    userInfo,
		Token:       token,
		MenuList:    menuList,
		Permissions: permissions,
	}, nil
}
